import axios from 'axios';
import router from '../router/router';
import {message} from 'ant-design-vue';
import QS from 'qs';
import website from "../config/website";
import store from '../store/store';

// timeout
axios.defaults.timeout = 10000;

// 请求拦截器
axios.interceptors.request.use(
    config => {
        let key = store.state.key;
        if (key) {
            // get
            if (config.method == 'get') {
                config.params = Object.assign(config.params || {}, {key: key});
            }
            // post
            else if (config.method == 'post') {
                let data = Object.assign(config.data || {}, {key: key});
                config.data = QS.stringify(data);
            }
        }
        return config;
    },
    error => {
        return Promise.error(error);
    }
);

// 响应拦截器
axios.interceptors.response.use(
    response => {
        let data = response.data,
            status = response.status;
        if (status === 200) {
            let code = data.code,
                msg = data.msg || website.msg.error;
            //console.log(status, code, msg);
            if (code === 0) {
                return Promise.resolve(response);
            }
            // token 过期
            else if (code === 999) {
                message.error(msg);
                // 退出登录
                store.dispatch('out').then(res => {
                    router.push('/');
                }).catch(err => {
                    console.log(err);
                    router.push('/');
                });
            }
            // 其它
            else {
                return Promise.reject(response);
            }
        } else {
            return Promise.reject(response);
        }
    },
    // 服务器状态码不是2开头的的情况
    error => {
        if (error.status) {
            //定义错误码
            if (error.status == 500) {
                message.error('服务器错误' || website.msg.error);
            } else {
                return Promise.reject(error.response);
            }
        }
    }
);

/**
 * GET
 * @param url
 * @param params
 * @returns {Promise<unknown>}
 */
export function get(url, params, isToken = false) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: Object.assign(params || {}, isToken ? {token: store.state.token} : {}),
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data);
        })
    });
}

/**
 * POST
 * @param url
 * @param data
 * @returns {Promise<unknown>}
 */
export function post(url, data, isToken = false) {
    return new Promise((resolve, reject) => {
        axios.post(url, Object.assign(data || {}, isToken ? {token: store.state.token} : {}))
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data);
            })
    });
}
